package com.schoolMall.service.impl;

import com.schoolMall.cache.RedisCache;
import com.schoolMall.dao.HeadLineDao;
import com.schoolMall.domain.HeadLine;
import com.schoolMall.service.HeadLineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author:zyh
 * @Time:2021-09-03-12:23
 * @email:1269231889@qq.com
 */
@Service
public class HeadLineServiceImpl implements HeadLineService {
    @Autowired
    private HeadLineDao headLineDao;
    @Autowired
    private RedisCache redisCache;

    private static String HEAD_LINE_KEY = "head_line_query";

    @Override
    public List<HeadLine> queryHeadLineByCondition(HeadLine headLineCondition) {
        List<HeadLine> headLineList = new ArrayList<>();
        if (Objects.isNull(headLineCondition) || Objects.isNull(headLineCondition.getEnableStatus())) {
            headLineList = queryCacheOrDb(headLineCondition);
        }
        HEAD_LINE_KEY = HEAD_LINE_KEY + "_" + headLineCondition.getEnableStatus();
        headLineList = queryCacheOrDb(headLineCondition);
        return headLineList;
    }


    private List<HeadLine> queryCacheOrDb(HeadLine headLine) {
        List<HeadLine> headLineList = new ArrayList<>();
        if (redisCache.exists(HEAD_LINE_KEY)) {
            headLineList = (List<HeadLine>) redisCache.get(HEAD_LINE_KEY);
        } else {
            headLineList = headLineDao.queryHeadLine(headLine);
            boolean set = redisCache.set(HEAD_LINE_KEY, headLineList);
        }
        return headLineList;
    }
}
